package com.taobao.fanli.service;

import com.taobao.fanli.dao.mapper.OrderMapper;
import com.taobao.fanli.dao.mapper.UserOrderMapper;
import com.taobao.fanli.dao.model.Order;
import com.taobao.fanli.dao.model.Transaction;
import com.taobao.fanli.dao.model.UserOrder;
import com.taobao.fanli.utils.DateUtil;
import com.taobao.fanli.utils.ExcelUtils;
import com.taobao.fanli.vo.Login;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author:xiaolei
 * @date:2018/6/2
 */
@Service
public class OrderService {

    private static final Logger logger = LoggerFactory.getLogger(OrderService.class);

    @Resource
    private OrderMapper orderMapper;
    @Resource
    private TaobaoApiService taobaoApiService;
    @Resource
    private UserOrderMapper userOrderMapper;
    @Resource
    private UserService userService;
    @Resource
    private TransactionService transactionService;

    public void insertOrderData(String path) throws IOException {
        List<List<Object>> lists = ExcelUtils.readExcel(new File(path));
        lists.remove(0);
        for (List<Object> list : lists){
            String goodsId = (String) list.get(3);
            String orderNumber = (String) list.get(25);
            //判断添加还是修改
            if(!StringUtils.isEmpty(goodsId) && !StringUtils.isEmpty(orderNumber)){
                Order order = orderMapper.selectByGoodsIdAndOrderNumber(goodsId, orderNumber);
                if(order == null){
                    insertOne(list);
                }else{
                    updateOne(order, list);
                }
            }
        }
    }

    private void updateOne(Order order, List<Object> list) {
        setParam(list, order);
        try{
            orderMapper.updateByPrimaryKeySelective(order);
            updateRecAndFroAndRecRedpack(order);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("更新失败:",e);
        }
    }

    public void insertOne(List<Object> list){
        Order order = new Order();
        order.setId(null);
        setParam(list, order);
        try {
            orderMapper.insertSelective(order);
            updateRecAndFroAndRecRedpack(order);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("插入失败:",e);
        }
    }

    //初始化参数
    private void setParam(List<Object> list, Order order) {
        String createAt = (String) list.get(0);
        if(!StringUtils.isEmpty(createAt)){
            order.setCreateAt(createAt);
        }
        String clickAt = (String) list.get(1);
        if(!StringUtils.isEmpty(clickAt)){
            order.setClickAt(clickAt);
        }
        String goodsInfo = (String) list.get(2);
        if(!StringUtils.isEmpty(goodsInfo)){
            order.setGoodsInfo(goodsInfo);
        }
        String goodsId = (String) list.get(3);
        if(!StringUtils.isEmpty(goodsId)){
            order.setGoodsId(goodsId);
            Map<String, String> goodsMap = taobaoApiService.getGoodsInfo(goodsId);
            if (goodsMap != null){
                order.setGoodsUrl(goodsMap.get("goodsUrl"));
                order.setGoodsPic(goodsMap.get("goodsPic"));
                order.setGoodsTitle(goodsMap.get("goodsTitle"));
            }
        }
        String manager = (String) list.get(4);
        if(!StringUtils.isEmpty(manager)){
            order.setManager(manager);
        }
        String shop = (String) list.get(5);
        if(!StringUtils.isEmpty(shop)){
            order.setShop(shop);
        }
        String goodsNumber = (String) list.get(6);
        if(!StringUtils.isEmpty(goodsNumber)){
            order.setGoodsNumber(goodsNumber);
        }
        String goodsPrice = (String) list.get(7);
        if(!StringUtils.isEmpty(goodsPrice)){
            order.setGoodsPrice(goodsPrice);
        }
        String orderState = (String) list.get(8);
        if(!StringUtils.isEmpty(orderState)){
            order.setOrderState(orderState);
            byte orderStatus = 0;
            switch (orderState){
                case "订单结算":
                    orderStatus = 1;
                    break;
                case "订单付款":
                    orderStatus = 2;
                    break;
                case "订单失效":
                    orderStatus = 3;
                    break;
                case "订单成功":
                    orderStatus = 4;
                    break;
            }
            order.setOrderStatus(orderStatus);
        }
        String orderType = (String) list.get(9);
        if(!StringUtils.isEmpty(orderType)){
            order.setOrderType(orderType);
        }
        String incomeRatio = (String) list.get(10);
        if(!StringUtils.isEmpty(incomeRatio)){
            order.setIncomeRatio(incomeRatio);
        }
        String divideRatio = (String) list.get(11);
        if(!StringUtils.isEmpty(divideRatio)){
            order.setDivideRatio(divideRatio);
        }
        String pay = (String) list.get(12);
        if(!StringUtils.isEmpty(pay)){
            order.setPay(pay);
        }
        String effect = (String) list.get(13);
        if(!StringUtils.isEmpty(effect)){
            order.setEffect(effect);
        }
        String finishPay = (String) list.get(14);
        if(!StringUtils.isEmpty(finishPay)){
            order.setFinishPay(finishPay);
        }
        String forecastIncome = (String) list.get(15);
        if(!StringUtils.isEmpty(forecastIncome)){
            order.setForecastIncome(forecastIncome);
        }
        String finishTime = (String) list.get(16);
        if(!StringUtils.isEmpty(finishTime)){
            order.setFinishTime(finishTime);
        }
        String moneyRatio = (String) list.get(17);
        double floor = 0;
        if(!StringUtils.isEmpty(moneyRatio)){
            order.setMoneyRatio(moneyRatio);
            floor = Math.floor(Double.parseDouble(moneyRatio.replace("%", "")) * 0.9);
        }
        String money = (String) list.get(18);
        if(!StringUtils.isEmpty(money)){
            order.setMoney(money);
        }
        String subsidyRatio = (String) list.get(20);
        if(!StringUtils.isEmpty(subsidyRatio)){
            order.setSubsidyRatio(subsidyRatio);
        }
        String subsidyMoney = (String) list.get(21);
        if(!StringUtils.isEmpty(subsidyMoney)){
            order.setSubsidyMoney(subsidyMoney);
        }
        if(!StringUtils.isEmpty(money) && !money.equals("0")) {
            String realMoney = new BigDecimal(pay).multiply(new BigDecimal(String.valueOf(floor
                    / 100))).add(new BigDecimal(subsidyMoney)).toString();
            order.setRealMoney(realMoney);
        }else{
            order.setRealMoney("0");
        }
        String subsidyType = (String) list.get(22);
        if(!StringUtils.isEmpty(subsidyType)){
            order.setSubsidyType(subsidyType);
        }
        String plantform = (String) list.get(23);
        if(!StringUtils.isEmpty(plantform)){
            order.setPlantform(plantform);
        }
        String thirdFrom = (String) list.get(24);
        if(!StringUtils.isEmpty(thirdFrom)){
            order.setThirdFrom(thirdFrom);
        }
        String orderNumber = (String) list.get(25);
        if(!StringUtils.isEmpty(orderNumber)){
            order.setOrderNumber(orderNumber);
        }
        String typeName = (String) list.get(26);
        if(!StringUtils.isEmpty(typeName)){
            order.setTypeName(typeName);
        }
        String mediaId = (String) list.get(27);
        if(!StringUtils.isEmpty(mediaId)){
            order.setMediaId(mediaId);
        }
        String mediaName = (String) list.get(28);
        if(!StringUtils.isEmpty(mediaName)){
            order.setMediaName(mediaName);
        }
        String adId = (String) list.get(29);
        if(!StringUtils.isEmpty(adId)){
            order.setAdId(adId);
        }
        String adName = (String) list.get(30);
        if(!StringUtils.isEmpty(adName)){
            order.setAdName(adName);
        }
    }

    //更新用户各种金额
    private void updateRecAndFroAndRecRedpack(Order order) throws ParseException {
        UserOrder userOrder = userOrderMapper.getOneByOrderNumber(order.getOrderNumber(),
                order.getId(),0);
        if(userOrder != null) {
            userOrder.setOrderId(order.getId());
            userOrder.setState(1);
            userOrderMapper.updateDynamic(userOrder);
            //流水帐存储
            transactionMethod(order, userOrder);

            //更新用户
            userService.updateReceiceAndFrozenAndReceiveRedpack(userOrder.getUserId());
        }
    }
    //流水帐存储
    private void transactionMethod(Order order, UserOrder userOrder) throws ParseException {
        Date day = DateUtil.getDay(new Date(), -15);
        Date createAt = DateUtil.sdf.parse(order.getCreateAt());
        if(day.compareTo(createAt) >= 0){
            //超过15天
            if(order.getOrderStatus() == 1 || order.getOrderStatus() == 4){
                //可领取
                //可领取流水号
                Transaction receiveTransaction = transactionService.selectByUserIdAndTypeAndFromAndOrderId(userOrder.getUserId(),
                        TransactionService.RECEIVEMONEYSTATE, TransactionService.ORDERFROM, order.getId());
                if(receiveTransaction == null){
                    //冻结流水号
                    Transaction frozonTransaction = transactionService.selectByUserIdAndTypeAndFromAndOrderId(userOrder.getUserId(),
                            TransactionService.FROZENMONEYSTATE, TransactionService.ORDERFROM, order.getId());
                    if(frozonTransaction != null){
                        //减冻结金额
                        transactionService.insertOne(userOrder.getUserId(), new BigDecimal(order.getRealMoney()).negate(),  TransactionService.FROZENMONEYSTATE, TransactionService.ORDERFROM, order.getId());
                    }
                    //加可提取金额
                    transactionService.insertOne(userOrder.getUserId(), new BigDecimal(order.getRealMoney()),  TransactionService.RECEIVEMONEYSTATE, TransactionService.ORDERFROM, order.getId());
                }
            }else if(order.getOrderStatus() == 2){
                //冻结
                //冻结金额
                Transaction frozonTransaction = transactionService.selectByUserIdAndTypeAndFromAndOrderId(userOrder.getUserId(),
                        TransactionService.FROZENMONEYSTATE, TransactionService.ORDERFROM, order.getId());
                if(frozonTransaction == null){
                    //加冻结金额
                    transactionService.insertOne(userOrder.getUserId(), new BigDecimal(order.getRealMoney()),  TransactionService.FROZENMONEYSTATE, TransactionService.ORDERFROM, order.getId());
                }
            }else{
                //订单失效
                Transaction receiveTransaction = transactionService.selectByUserIdAndTypeAndFromAndOrderId(userOrder.getUserId(),
                        TransactionService.RECEIVEMONEYSTATE, TransactionService.ORDERFROM, order.getId());
                if(receiveTransaction == null){
                    //冻结流水号
                    Transaction frozonTransaction = transactionService.selectByUserIdAndTypeAndFromAndOrderId(userOrder.getUserId(),
                            TransactionService.FROZENMONEYSTATE, TransactionService.ORDERFROM, order.getId());
                    if(frozonTransaction != null){
                        //减冻结金额
                        transactionService.insertOne(userOrder.getUserId(), new BigDecimal(order.getRealMoney()).negate(),  TransactionService.FROZENMONEYSTATE, TransactionService.ORDERFROM, order.getId());
                    }
                } else{
                    //减可提取金额
                    transactionService.insertOne(userOrder.getUserId(), new BigDecimal(order.getRealMoney()).negate(),  TransactionService.RECEIVEMONEYSTATE, TransactionService.ORDERFROM, order.getId());
                }
            }
        }else{
            //不超过15天   冻结
            //冻结流水号
            Transaction frozonTransaction = transactionService.selectByUserIdAndTypeAndFromAndOrderId(userOrder.getUserId(),
            TransactionService.FROZENMONEYSTATE, TransactionService.ORDERFROM, order.getId());
            if(order.getOrderStatus() == 3){
                if(frozonTransaction != null){
                    //减冻结金额
                    transactionService.insertOne(userOrder.getUserId(), new BigDecimal(order.getRealMoney()).negate(),  TransactionService.FROZENMONEYSTATE, TransactionService.ORDERFROM, order.getId());
                }
            }else{
                if(frozonTransaction == null){
                    //加冻结金额
                    transactionService.insertOne(userOrder.getUserId(), new BigDecimal(order.getRealMoney()),  TransactionService.FROZENMONEYSTATE, TransactionService.ORDERFROM, order.getId());
                }
            }
        }
    }

    public Order selectOrderInfo(Integer orderId) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if(order.getOrderStatus() == 2 || order.getOrderStatus() == 4){
            order.setMoney(order.getEffect());
        }else if(order.getOrderStatus() == 1){
            order.setMoney(order.getRealMoney());
        }
        return order;
    }

    public void insertUserOrderData(String path, Login login) throws IOException, ParseException {
        List<List<Object>> lists = ExcelUtils.readExcel(new File(path));
        lists.remove(0);
        for (List<Object> list : lists){
            String orderNumber = (String) list.get(0);
            insertUserOrder(orderNumber, login);
        }
    }

    public void insertUserOrder(String orderNumber,Login login) throws RuntimeException, ParseException {
        UserOrder userOrder = userOrderMapper.getOneByOrderNumber(orderNumber, null,0);
        if(userOrder == null){
            userOrder = new UserOrder();
            List<Order> orders = orderMapper.selectOrderInfo(orderNumber);

            userOrder.setOrderNumber(orderNumber);
            userOrder.setUserId(login.getId());
            if(orders == null || orders.isEmpty()){
                userOrder.setState(0);
                userOrderMapper.insertDynamic(userOrder);
                throw new RuntimeException("订单已收录");
            }else{
                for (Order order : orders){
                    userOrder.setOrderId(order.getId());
                    userOrder.setState(1);
                    UserOrder oneByOrderNumber = userOrderMapper.getOneByOrderNumber(orderNumber,
                            order.getId(), 1);
                    if(oneByOrderNumber == null){
                        userOrderMapper.insertDynamic(userOrder);
                    }
                    transactionMethod(order, userOrder);
                }
                //更新用户
                userService.updateReceiceAndFrozenAndReceiveRedpack(login.getId());
            }
        }else{
            if(userOrder.getState() == 0){
                throw new RuntimeException("订单已收录");
            }
            List<Order> orders = orderMapper.selectOrderInfo(orderNumber);
            if(orders != null && !orders.isEmpty()){
                for (Order order : orders){
                    userOrder.setOrderId(order.getId());
                    userOrder.setState(1);
                    userOrder.setUserId(login.getId());
                    userOrderMapper.updateDynamic(userOrder);
                    transactionMethod(order, userOrder);
                }
                //更新用户
                userService.updateReceiceAndFrozenAndReceiveRedpack(login.getId());
            }
        }
    }
}
